import Vue from 'vue'
import axios from 'axios'
import router from '@/router'

const martin = new Vue()
const Axios = axios.create({
  baseURL: 'http://111.231.55.237:3001',
  // baseURL: 'http://127.0.0.1:3000',
  timeout: 10000
  // transformRequest(data) {
  //   return qs.stringify(data)
  // }
})

// axios.defaults.headers.common['Authorization'] = window.localStorage.access_token
// axios.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8'
Axios.interceptors.request.use((config) => {
  if (!config.url.includes('register') && !config.url.includes('login')) {
    config.headers = {
      Authorization: 'Bearer ' + window.localStorage.access_token
    }
  }
  if (config.method === 'post') {
    // config.data = JSON.stringify(config.data)
    // config.headers['Content-Type'] = 'multipart/form-data'
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

Axios.interceptors.response.use((response) => {
  // Do something with response data
  return response
}, (error) => {
  if (error.response && error.response.status === 401) {
    martin.$message.error('登录失效')
    return void router.replace({name: 'MartinLogin'})
  }
  if (error.response && error.response.status === 500) {
    return void martin.$message.error(error.response.data.message)
  }
  // Do something with response error
  return Promise.reject(error)
})

export default {
  install(Vue) {
    Vue.prototype.$http = Axios
  }
}
